<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form small-top">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="调拨时间：" prop="createTime">
              <el-date-picker
                v-model="createTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
                @change="getArticleList"
              />
            </el-form-item>
            <el-form-item label="商品：" prop="goods_spu_id">
              <change-goods-input
                isInventory
                ref="changeGoodsInput"
                @clear="
                  () => {
                    this.form.goods_spu_id = '';
                  }
                "
                @sendValue="
                  (data) => {
                    this.form.goods_spu_id = data.id;
                  }
                "
              ></change-goods-input>
            </el-form-item>
            <el-form-item label="单号：" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="单号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
              <el-button @click="exportAllocation">导出</el-button>
            </MainFormBtn>
            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-show="moredata">
                <div class="clearfix"></div>
                <el-form-item label="调拨类型：" prop="type">
                  <el-select
                    v-model.trim="form.type"
                    placeholder="调拨类型"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(sort_status, index) in typeList"
                      :key="index"
                      :label="sort_status"
                      :value="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                    <el-button @click="exportAllocation">导出</el-button>
                  </MainFormBtn>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div>
            <el-button class="mainor_tea fill-height" @click="allotTypeDia">新增调拨</el-button>
            <el-button>
              <router-link to="/warehouse/allocation/split">分割关系</router-link>
            </el-button>
          </div>
        </div>
        <MainTable
          ref="allocationTable"
          :loading="listLoading"
          :columns="allocationColumns"
          :tableData="list.list.list || []"
          @selection-change="handleSelectionChange"
          :height="borderHeight + 20"
        >
          <template #customLeft>
            <el-table-column type="selection" align="center"></el-table-column>
          </template>
          <template v-slot:transfer="{ row }">
            <span :class="'type' + row.type">
              {{ typeList[row.type] }}
            </span>
          </template>
          <template v-slot:goods_content="{ row }">
            <span v-if="row.type == 1 || row.type == 2" class="goods-content-green">
              {{ row.goods_content }}
            </span>
            <span v-if="row.type == 3" class="goods-content-green goods-content-flex">
              <div class="flex-middle">
                <div>{{ row.goods_content }} </div>
                <div v-if="row.goods_content && row.allocationList">
                  --->
                </div>
              </div>
              <div class="flexs">
                <div v-for="(item, index) in row.allocationList" :key="index">
                  {{ item.newstr }}
                </div>
              </div>
            </span>
          </template>
          <template v-slot:created_at="{ row }">
            {{ parseTime(row.created_at) }}
          </template>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-link v-if="scope.row.type == 3" @click="openLook(scope.row.id)">查看</el-link>
            </template>
          </el-table-column>
        </MainTable>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>

        <!-- 调拨类型选择 -->
        <el-dialog
          title="调拨类型选择"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="allot_type_show"
          class="main_dialog_copy dialog400"
        >
          <div class="allot_type_container">
            <div class="upload_box flex-center" @click="changeAllotType(1)">
              同商品调拨
            </div>
            <div class="upload_box flex-center" @click="changeAllotType(2)">
              异商品调拨
            </div>
            <div class="upload_box flex-center" @click="changeAllotType(3)">
              白条分割
            </div>
          </div>
        </el-dialog>

        <!-- 同商品调拨 -->
        <el-dialog
          title="同商品调拨"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="closeDia(1)"
          :visible.sync="addedFormVisible"
          class="main_dialog dialog550"
        >
          <el-form
            :inline="false"
            :model="info"
            :rules="rules"
            class="demo-form-inline"
            ref="userListFrom1"
            label-width="140px"
          >
            <el-form-item label="选择商品：" prop="name">
              <allot-change-goods
                ref="sysncGoodsInput"
                url="sync"
                @clear="sysncClose"
                @sendValue="handleSelect"
              ></allot-change-goods>
            </el-form-item>
            <el-form-item label="选择调出SKU：" prop="stock_out_goods_spu_id">
              <el-select
                v-model="info.stock_out_goods_spu_id"
                placeholder="选择调出SKU"
                class="wid300"
                @change="spuChange(1, $event)"
              >
                <template v-for="item in formsp.arry">
                  <el-option
                    :key="item.id"
                    :label="item.spu_name.title"
                    :value="item.id"
                    v-if="item.id != info.storage_goods_spu_id"
                  >
                    <span
                      :style="{ opacity: item.is_inventory == 2 ? 0.5 : 1 }"
                      >{{ item.spu_name.title }}</span
                    >
                  </el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="调出SKU库存：" prop="inventory_num">
              <el-input
                v-model.trim="info.inventory_num"
                placeholder="调出SKU库存"
                clearable
                :disabled="true"
                class="wid300"
              ></el-input>
            </el-form-item>
            <el-form-item label="调出数量：" prop="stock_out_num">
              <el-input
                v-model.trim="info.stock_out_num"
                placeholder="调出数量"
                class="wid300"
                clearable
                @clear="numberClear"
                @change="numberChange"
                @input="stockInput"
              ></el-input>
            </el-form-item>
            <el-form-item label="选择调入SKU：" prop="storage_goods_spu_id">
              <el-select
                v-model.trim="info.storage_goods_spu_id"
                placeholder="选择调入SKU"
                class="wid300"
                @change="spuChange(2, $event)"
              >
                <template v-for="item in formsp.arry">
                  <el-option
                    :key="item.id"
                    :label="item.spu_name.title"
                    :value="item.id"
                    v-if="item.id != info.stock_out_goods_spu_id"
                  >
                    <span
                      :style="{ opacity: item.is_inventory == 2 ? 0.5 : 1 }"
                      >{{ item.spu_name.title }}</span
                    >
                  </el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="调入数量：">
              <el-input
                v-model.trim="info.transfer"
                placeholder="调入数量"
                clearable
                :disabled="true"
                class="wid300"
              ></el-input>
            </el-form-item>
            <el-form-item label="互调比：">
              <el-input
                v-model.trim="info.ratio"
                placeholder="互调比"
                clearable
                :disabled="true"
                class="wid300"
              ></el-input>
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
              <el-input
                v-model.trim="info.remark"
                placeholder="备注"
                clearable
                class="wid300"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="(addedFormVisible = false), sysncClose()"
              >取 消</el-button
            >
            <el-button type="primary" @click="setupmine" v-repeatClick
              >保 存</el-button
            >
          </div>
        </el-dialog>

        <!-- 异商品调拨 -->
        <el-dialog
          title="异商品调拨"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="asyncGoodsVisible"
          @close="closeDia(2)"
          class="main_dialog dialog550"
        >
          <el-form
            :inline="false"
            :model="asyncGoodsForm"
            :rules="rules"
            class="demo-form-inline"
            ref="asyncGoodsForm"
            label-width="140px"
          >
            <el-form-item label="调出商品：" prop="name">
              <allot-change-goods
                isInventory
                ref="asysncGoodsInput1"
                :form="asyncGoodsForm"
                :type="1"
                url="async"
                @clear="asyncClear(1)"
                @sendValue="
                  (item) => {
                    handleSelectAsync(item, 1);
                  }
                "
              ></allot-change-goods>
            </el-form-item>
            <!-- <el-form-item label="选择调出SKU：" prop="stock_out_goods_spu_id">
              <el-select
                v-model.trim="asyncGoodsForm.stock_out_goods_spu_id"
                placeholder="选择调出SKU"
                class="wid300"
                @change="asyncSpuChange(1)"
              >
                <template v-for="item in stock_out_goods_spu">
                  <el-option
                    :key="item.id"
                    :label="item.spu_name.title"
                    :value="item.id"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item> -->
            <el-form-item label="系统库存：">
              <el-input
                v-model.trim="asyncGoodsForm.inventory_num"
                placeholder="系统库存"
                clearable
                :disabled="true"
                class="wid300"
              ></el-input>
            </el-form-item>
            <el-form-item label="调出数量：" prop="stock_out_num">
              <el-input
                v-model.trim="asyncGoodsForm.stock_out_num"
                placeholder="调出数量"
                class="wid300"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="调入商品：" prop="storage_name">
              <allot-change-goods
                isInventory
                ref="asysncGoodsInput2"
                :form="asyncGoodsForm"
                :type="2"
                url="async"
                @clear="asyncClear(2)"
                @sendValue="
                  (item) => {
                    handleSelectAsync(item, 2);
                  }
                "
              ></allot-change-goods>
            </el-form-item>
            <!-- <el-form-item label="选择调入SKU：" prop="storage_goods_spu_id">
              <el-select
                v-model.trim="asyncGoodsForm.storage_goods_spu_id"
                placeholder="选择调入SKU"
                class="wid300"
              >
                <template v-for="item in storage_goods_spu">
                  <el-option
                    :key="item.id"
                    :label="item.spu_name.title"
                    :value="item.id"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item> -->

            <el-form-item label="调入数量：" prop="storage_num">
              <el-input
                v-model.trim="asyncGoodsForm.storage_num"
                placeholder="调入数量"
                class="wid300"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
              <el-input
                v-model.trim="asyncGoodsForm.remark"
                placeholder="备注"
                clearable
                class="wid300"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="(asyncGoodsVisible = false), sysncClose()"
              >取 消</el-button
            >
            <el-button type="primary" @click="asyncSetupmine" v-repeatClick
              >保 存</el-button
            >
          </div>
        </el-dialog>

        <!-- 白条分割 -->
        <el-dialog
          width="53%"
          title="白条分割"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="closeDia(3)"
          :visible.sync="iousVisible"
          class="main_dialog dialog550"
        >
          <div class="maincla_form">
            <el-form
              :rules="rules"
              :inline="false"
              :model="iousGoodsForm"
              class="demo-form-inline"
              ref="iousGoodsForm"
              label-width="140px"
            >
              <div style="display: flex">
                <div>
                  <el-form-item label="选择白条：" prop="">
                    <el-autocomplete
                      v-model="iousGoodsForm.value"
                      ref="iousSelect"
                      class="wid240 main_comm"
                      @clear="clearData"
                      :fetch-suggestions="
                        (queryString, cb) => {
                          iousSearchAsync(queryString, cb);
                        }
                      "
                      placeholder="商品/助记码/编码"
                      clearable
                      :trigger-on-focus="false"
                      value-key="name"
                      @select="
                        (item) => {
                          iousleSelect(item);
                        }
                      "
                    >
                    </el-autocomplete>
                  </el-form-item>

                  <el-form-item label="单位：" prop="">
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.ious_unit"
                      placeholder="单位"
                      class="wid240"
                    ></el-input>
                  </el-form-item>

                  <el-form-item label="库存数量：" prop="ious_inventory">
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.ious_inventory"
                      placeholder="库存数量"
                      class="wid240"
                    ></el-input>
                  </el-form-item>

                  <el-form-item label="库存单价：" prop="price">
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.price"
                      placeholder="库存单价"
                      class="wid240"
                    ></el-input>
                  </el-form-item>

                  <el-form-item label="库存总价：" prop="money">
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.money"
                      placeholder="库存总价"
                      class="wid240"
                    ></el-input>
                  </el-form-item>
                </div>

                <div>
                  <el-form-item label="初始白条重量：" prop="ious_initnum">
                    <!-- <el-input
                      clearable
                      v-model.trim="iousGoodsForm.ious_initnum"
                      placeholder="初始白条重量"
                      class="wid240"
                      @change="initNum"
                    ></el-input> -->
                    <el-input-number
                      class="wid240"
                      placeholder="初始白条重量"
                      v-model.trim="iousGoodsForm.ious_initnum"
                      :precision="2"
                      @change="initNum"
                      :controls="false"
                      :min="nullNum"
                    ></el-input-number>
                  </el-form-item>

                  <el-form-item prop="ious_Allprice">
                    <span slot="label">
                      <el-tooltip
                        class="item marginRight5 mainor_tei"
                        effect="dark"
                        placement="bottom"
                      >
                        <div slot="content">
                          初始白条总价 = 初始白条重量 * 库存单价
                        </div>
                        <i class="el-icon-question"></i> </el-tooltip
                      >初始白条总价：
                    </span>
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.ious_Allprice"
                      placeholder="初始白条总价"
                      class="wid240"
                    ></el-input>
                  </el-form-item>

                  <el-form-item prop="child_Allnum">
                    <span slot="label">
                      <el-tooltip
                        class="item marginRight5 mainor_tei"
                        effect="dark"
                        placement="bottom"
                      >
                        <div slot="content">所有子料分割数量之和</div>
                        <i class="el-icon-question"></i> </el-tooltip
                      >子料总重量：
                    </span>
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.child_Allnum"
                      placeholder="子料总重量"
                      class="wid240"
                    ></el-input>
                  </el-form-item>

                  <el-form-item prop="loss_num">
                    <span slot="label">
                      <el-tooltip
                        class="item marginRight5 mainor_tei"
                        effect="dark"
                        placement="bottom"
                      >
                        <div slot="content">
                          损耗数量 = 初始白条重量 - 子料总重量
                        </div>
                        <i class="el-icon-question"></i> </el-tooltip
                      >损耗数量：
                    </span>
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.loss_num"
                      placeholder="损耗数量"
                      class="wid240"
                    ></el-input>
                  </el-form-item>

                  <el-form-item prop="storage_price">
                    <span slot="label">
                      <el-tooltip
                        class="item marginRight5 mainor_tei"
                        effect="dark"
                        placement="bottom"
                      >
                        <div slot="content">
                          子料入库单价 = 初始白条总价 / 子料总重量
                        </div>
                        <i class="el-icon-question"></i> </el-tooltip
                      >子料入库单价：
                    </span>
                    <el-input
                      :disabled="true"
                      v-model.trim="iousGoodsForm.storage_price"
                      placeholder="子料入库单价"
                      class="wid240"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>

              <el-form-item label="备注：" prop="remark">
                <el-input
                  v-model.trim="iousGoodsForm.remark"
                  placeholder="备注"
                  clearable
                  class="wid600"
                ></el-input>
              </el-form-item>

              <!-- 表格 -->
              <div class="main_table main_taf marginTop0">
                <el-table
                  ref="multipleTable"
                  :data="iousGoodsForm.storage_list"
                  element-loading-text="加载中"
                  fit
                  border
                  highlight-current-row
                  :header-cell-class-name="this.$verticaline"
                >
                  <el-table-column label="序号">
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        {{ scope.$index + 1 }}
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="子料名称"
                    show-overflow-tooltip
                    prop="name"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        {{ scope.row.name }}【{{ scope.row.unit }}】
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="单位"
                    show-overflow-tooltip
                    prop="unit"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        {{ scope.row.unit }}
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="分割数量"
                    prop="storage_num"
                    :show-overflow-tooltip="true"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :rules="rules.storage_num"
                        label-width="0"
                        :prop="'storage_list.' + scope.$index + '.storage_num'"
                      >
                        <el-input
                          class="wid110"
                          :ref="'storage_num' + scope.$index"
                          v-model.trim="scope.row.storage_num"
                          placeholder="分割数量"
                          @change="numFill"
                          clearable
                          @clear="cleradata"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="备注"
                    prop="remark"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        <el-input
                          v-model.trim="scope.row.remark"
                          placeholder="备注"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="管理操作"
                    align="left"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        <el-link type="danger" @click="delchild(scope.$index)"
                          >删除</el-link
                        >
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form>

            <div slot="footer" class="dialog_footer">
              <el-button @click="(iousVisible = false), iousClose()"
                >取 消</el-button
              >
              <el-button type="primary" @click="iousSubmit" v-repeatClick
                >保 存</el-button
              >
            </div>
          </div>
        </el-dialog>
        <!-- SKU调拨导出 -->
        <ExportDialog :visible.sync="exportVisible" :typeList="typeList"></ExportDialog>
      </div>
    </div>
  </div>
</template>

<script>
const shuju = {
  formsp: {
    name: [],
    arry: [],
    value: "",
  },
};
import { allocationColumns } from './mockData';
import { mixins } from "@/mixins/index.js";
import {
  allocation_index,
  allocation_add,
  allocation_getGoods,
  allocation_getGoodsSpu,
  export_allocation_info,
  allocation_addDiff,
  search_relationship,
  ious_add,
} from "@/api/warehouse/warehouseAllocation";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import rules from "@/rules/warehouse/warehouseAllocation";
import dateOption from "@/options/dateOption";
import { parseTime } from "@/utils/index";
import AllotChangeGoods from "@/views/warehouse/components/AllotChangeGoods";
import ExportDialog from "@/views/warehouse/components/allocation/exportDialog.vue";

let stock_package_num = "";
let storage_package_num = "";

export default {
  mixins: [mixins],
  components: { AllotChangeGoods, ExportDialog },
  data() {
    return {
      allocationColumns,
      // 时间
      parseTime,
      // 验证
      rules,
      typeList: {},
      // 增加
      info: {
        goods_id: "",
        stock_out_goods_spu_id: null,
        storage_goods_spu_id: null,
        stock_out_num: "",
        remark: "",
        inventory_num: "",
        name: "",
        transfer: "",
        ratio: "",
        type: 1,
      },
      formsp: {
        name: [],
        arry: [],
        value: "",
      },
      addedFormVisible: false,

      // 异步商品调拨
      asyncGoodsVisible: false,
      asyncGoodsForm: {
        goods_id: "",
        name: "",
        stock_out_goods_spu_id: "",
        inventory_num: "",
        stock_out_num: "", //调出数量
        storage_goods_id: "",
        storage_name: "",
        storage_goods_spu_id: "",
        storage_num: "",
        remark: "",
        type: 2,
      },
      storage_goods_spu: [],
      stock_out_goods_spu: [],
      // 调拨类型选择
      allot_type_show: false,

      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: [],
      },
      listLoading: false,
      // 搜索
      form: {
        goods_spu_id: "",
        order_sn: "",
        start_time: "",
        end_time: "",
        type: null,
      },
      createTime: [],
      pickerOptions: dateOption,
      // 选择全部
      selectArr: [],
      //白条分割
      iousVisible: false,
      iousGoodsForm: {
        storage_list: [],
        stock_out_goods_spu_id: "",
        type: 3,
        ious_unit: "",
        ious_inventory: "",
        value: "",
        remark: "",
        price: "",
        money: "",
        ious_initnum: "",
        ious_Allprice: 0,
        child_Allnum: 0,
        loss_num: 0,
        storage_price: 0,
      },
      order_money_limit_min: "",
      nullNum: null,
      moredata: false,
      exportVisible: false, // SKU调拨导出弹框状态
    };
  },
  created() {
    // 列表
    this.getNumerical(220);
    this.allocation_index();
  },
  methods: {
    openLook(id) {
      this.$router.push(`/warehouse/allocation/see/${id}`)
    },
    reset() {
      this.$refs['userListFrom'].resetFields();
      this.createTime = []
      this.$refs['changeGoodsInput'].name = '';
      this.allocation_index()
    },
    more() {
      this.moredata = !this.moredata;
    },
    getSearchFor() {
      this.getArticleList();
    },
    startGetting() {
      this.getArticleList();
    },
    // 同步弹窗关闭
    sysncClose() {
      this.info = {
        goods_id: "",
        stock_out_goods_spu_id: null,
        storage_goods_spu_id: null,
        stock_out_num: "",
        remark: "",
        inventory_num: "",
        name: "",
        transfer: "",
        ratio: "",
        type: 1,
      };
      this.$refs["sysncGoodsInput"].name = "";
      this.formsp = JSON.parse(JSON.stringify(shuju.formsp));
      this.$refs["userListFrom1"].clearValidate();
    },
    // 异步弹窗关闭
    asyncClose() {
      this.asyncGoodsForm = {
        goods_id: "",
        name: "",
        stock_out_goods_spu_id: "",
        inventory_num: "",
        stock_out_num: "", //调出数量
        storage_goods_id: "",
        storage_name: "",
        storage_goods_spu_id: "",
        storage_num: "",
        remark: "",
        type: 2,
      };
      this.$refs["asysncGoodsInput1"].name = "";
      this.$refs["asysncGoodsInput2"].name = "";
      this.$refs["asyncGoodsForm"].clearValidate();
    },
    //白条分割
    iousClose() {
      this.iousGoodsForm = {
        storage_list: [],
        stock_out_goods_spu_id: "",
        type: 3,
        ious_unit: "",
        ious_inventory: "",
        value: "",
        remark: "",
        price: "",
        money: "",
        ious_initnum: "",
        ious_Allprice: 0,
        child_Allnum: 0,
        loss_num: 0,
        storage_price: 0,
      };
    },
    asyncClear(type) {
      switch (type) {
        case 1:
          this.asyncGoodsForm.goods_id = "";
          this.asyncGoodsForm.name = "";
          this.asyncGoodsForm.inventory_num = "";
          this.asyncGoodsForm.stock_out_goods_spu_id = "";
          this.$refs["asysncGoodsInput1"].name = "";
          break;
        case 2:
          this.asyncGoodsForm.storage_goods_id = "";
          this.asyncGoodsForm.storage_name = "";
          this.asyncGoodsForm.storage_goods_spu_id = "";
          this.$refs["asysncGoodsInput2"].name = "";
          break;
      }
    },
    // 弹窗关闭
    closeDia(type) {
      this.allot_type_show = false;
      switch (type) {
        case 1:
          this.$nextTick(() => {
            this.sysncClose();
          });
          break;
        case 2:
          this.$nextTick(() => {
            this.asyncClose();
          });
          break;
        case 3:
          this.$nextTick(() => {
            this.iousClose();
          });
          break;
      }
    },
    // 同步商品确认
    setupmine() {
      this.$refs["userListFrom1"].validate((valid) => {
        if (valid) {
          let info = JSON.parse(JSON.stringify(this.info));
          let { inventory_num, name, transfer, ratio, ...from } = info;
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name, from)) +
                  apiUrl().appsecret
              ),
            },
            apiUrl().name,
            from
          );
          allocation_add(data).then((res) => {
            this.addedFormVisible = false;
            if (res.errcode == 0) {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.current.page = 1;
              this.allocation_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    //异步商品确认
    asyncSetupmine() {
      this.$refs["asyncGoodsForm"].validate((valid) => {
        if (valid) {
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            this.asyncGoodsForm
          );
          allocation_addDiff(data).then((res) => {
            if (res.errcode == 0) {
              this.asyncGoodsVisible = false;
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.current.page = 1;
              this.allocation_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        } else {
        }
      });
    },
    //白条分割商品确认
    iousSubmit() {
      let sz = JSON.parse(JSON.stringify(this.iousGoodsForm.storage_list));
      let list = sz.map((e) => {
        let { unit, name, price, num, ...sz } = e;
        return { ...sz };
      });
      let total = 0;
      let arrlist = [];
      let newtotal = 0;
      for (let i = 0; i < list.length; i++) {
        if (list[i].storage_num != "") {
          arrlist.push(list[i]);
          newtotal += Number(list[i].storage_num);
        } else {
          if (list[i].storage_num == "") {
            total += 1;
          }
        }
      }
      if (this.iousGoodsForm.ious_initnum == null) {
        this.$message.error("初始白条重量不能为空");
        return;
      }
      if (!/^(\d+\.?)?\d{0,2}$/.test(this.iousGoodsForm.ious_initnum)) {
        this.$message.error("请输入整数和小数");
        return;
      }
      if (total > 0) {
        this.$confirm(
          `列表中有${total}项子料没有分割数量，确认继续提交吗？`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            this.saveAddious(arrlist);
          })
          .catch(() => {});
      }
      if (newtotal) {
        if (newtotal > this.iousGoodsForm.ious_initnum) {
          this.$message.error("子料重量不能大于初始白条重量");
          return;
        } else {
          let newnum = 0;
          this.iousGoodsForm.storage_list.map((e) => {
            newnum = e.storage_num;
          });
          if (!/^(\d+\.?)?\d{0,2}$/.test(newnum)) {
            this.$message.error("请输入整数和小数");
            return;
          } else {
            this.$confirm(`确认提交吗？`, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "success",
            })
              .then(() => {
                this.saveAddious(arrlist);
              })
              .catch(() => {});
          }
        }
      }
      if (this.iousGoodsForm.storage_list.length == 0) {
        this.$message.error("子料信息不能为空");
        this.iousVisible = false;
      }
    },
    //保存
    saveAddious(val) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          loss_num: this.iousGoodsForm.loss_num,
          storage_price: this.iousGoodsForm.storage_price,
          stock_out_goods_spu_id: this.iousGoodsForm.stock_out_goods_spu_id,
          type: this.iousGoodsForm.type,
          remark: this.iousGoodsForm.remark,
          storage_list: val.length > 0 ? JSON.stringify(val) : [],
        }
      );
      ious_add(data).then((res) => {
        this.iousVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.current.page = 1;
          this.allocation_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      allocation_getGoods(data).then((res) => {
        if (res.errcode == 0) {
          var results = res.data.goods;
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    //白条分割商品搜索
    iousSearchAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      search_relationship(data).then((res) => {
        if (res.errcode == 0) {
          res.data.info.map((e) => {
            e.child_goods_spu_ids.map((c) => {
              c.remark = "";
              c.storage_num = "";
            });
          });
          let results = res.data.info;
          if (this.$refs.iousGoodsForm) {
            this.$refs.iousGoodsForm.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 异商品选择
    handleSelectAsync(item, type) {
      switch (type) {
        case 1:
          this.asyncGoodsForm.goods_id = item.goods_id;
          this.asyncGoodsForm.name = item.name;
          this.$refs["asyncGoodsForm"].clearValidate("name");
          this.asyncGoodsForm.inventory_num = item.inventory.num;
          this.asyncGoodsForm.stock_out_goods_spu_id = item.id;
          break;
        case 2:
          this.asyncGoodsForm.storage_goods_id = item.goods_id;
          this.asyncGoodsForm.storage_name = item.name;
          this.$refs["asyncGoodsForm"].clearValidate("storage_name");
          this.asyncGoodsForm.storage_goods_spu_id = item.id;
          break;
      }
    },
    // 异商品sku选择
    asyncSpuChange(type) {
      switch (type) {
        case 1:
          this.stock_out_goods_spu.map((e) => {
            if (this.asyncGoodsForm.stock_out_goods_spu_id == e.id) {
              this.asyncGoodsForm.inventory_num = e.inventory.num;
            }
          });
          break;
        case 2:
          break;
      }
    },
    // 同商品选择
    handleSelect(item) {
      this.info = {
        goods_id: "",
        stock_out_goods_spu_id: null,
        storage_goods_spu_id: null,
        stock_out_num: "",
        remark: "",
        inventory_num: "",
        name: "",
        transfer: "",
        ratio: "",
        type: 1,
      };
      this.formsp.name = item;
      this.info.goods_id = item.id;
      this.info.name = item.name;
      this.formsp.value = item.name;
      this.allocation_getGoodsSpu();
    },
    //白条分割商品选择
    iousleSelect(item) {
      this.iousGoodsForm.ious_unit = item.unit;
      this.iousGoodsForm.ious_inventory = item.num;
      this.iousGoodsForm.storage_list = item.child_goods_spu_ids;
      this.iousGoodsForm.stock_out_goods_spu_id = item.goods_spu_id;
      this.iousGoodsForm.price = item.price;
      this.iousGoodsForm.money = item.money;
    },
    allocation_getGoodsSpu() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                goods_id: formsp.name.id,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          goods_id: formsp.name.id,
        }
      );
      allocation_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          this.formsp.arry = res.data.list;
        } else {
          this.close();
          this.$message.error(res.errmsg);
        }
      });
      this.$refs["userListFrom1"].clearValidate();
    },
    spuChange(type, e) {
      const info = this.formsp.arry.find((item) => item.id === e);
      // 判断选中是否是调拨规格
      if (info && info.is_inventory == 2) {
        this.$message.error("此商品规格为辅助单位不可手动调拨");
        this.info.stock_out_goods_spu_id =
          type == 1 ? "" : this.info.stock_out_goods_spu_id;
        this.info.storage_goods_spu_id =
          type == 2 ? "" : this.info.storage_goods_spu_id;
        return;
      }
      this.formsp.arry.map((e) => {
        if (this.info.stock_out_goods_spu_id == e.id) {
          stock_package_num = e.package_num;
          if (type == 1) {
            this.info.inventory_num = e.inventory ? e.inventory.num : "0.00";
          }
        }
        if (this.info.storage_goods_spu_id == e.id) {
          storage_package_num = e.package_num;
        }
      });
      if (this.info.stock_out_goods_spu_id && this.info.storage_goods_spu_id) {
        this.info.ratio = `${parseFloat(stock_package_num)} / ${parseFloat(
          storage_package_num
        )}`;
        // this.$toFixed(
        //   parseFloat(stock_package_num) / parseFloat(storage_package_num)
        // );
      }
      if (parseFloat(this.info.ratio) && parseFloat(this.info.stock_out_num)) {
        this.info.transfer = this.$toFixed(
          (parseFloat(stock_package_num) *
            parseFloat(this.info.stock_out_num)) /
            parseFloat(storage_package_num)
        );
        // this.info.transfer = this.$toFixed(
        //   parseFloat(this.info.ratio) * parseFloat(this.info.stock_out_num)
        // );
      }
    },
    stockInput(val) {
      if (parseFloat(this.info.ratio) && parseFloat(val)) {
        this.info.transfer = this.$toFixed(
          (parseFloat(stock_package_num) * parseFloat(val)) /
            parseFloat(storage_package_num)
        );
        // this.info.transfer = this.$toFixed(
        //   parseFloat(this.info.ratio) * parseFloat(val)
        // );
      }
    },
    // 监听输入
    numberChange(val) {
      if (parseFloat(val) <= parseFloat(this.info.inventory_num)) {
        this.info.stock_out_num = parseFloat(val);
      } else {
        this.info.stock_out_num = parseFloat(this.info.inventory_num);
        this.info.transfer = this.$toFixed(
          (parseFloat(stock_package_num) * parseFloat(this.info.stock_out_num)) /
            parseFloat(storage_package_num)
        );
      }
    },
    initNum(val) {
      if (!this.iousGoodsForm.value) {
        this.$message.error("请先选择白条商品");
        this.iousGoodsForm.ious_initnum = "";
      } else {
        if (
          parseFloat(val) == 0 ||
          parseFloat(val) > parseFloat(this.iousGoodsForm.ious_inventory)
        ) {
          this.iousGoodsForm.ious_initnum = this.iousGoodsForm.ious_inventory;
          this.iousGoodsForm.ious_Allprice = this.$toFixed(
            parseFloat(this.iousGoodsForm.ious_initnum) *
              parseFloat(this.iousGoodsForm.price)
          );
          this.result();
        } else {
          this.iousGoodsForm.ious_Allprice = this.$toFixed(
            parseFloat(this.iousGoodsForm.ious_initnum) *
              parseFloat(this.iousGoodsForm.price)
          );
          this.result();
        }
      }
    },

    //分割数量输入
    numFill() {
      if (this.iousGoodsForm.ious_initnum == null) {
        this.$message.error("请先输入初始白条数量");
      } else {
        this.result();
      }
    },
    //分割数量清除事件
    cleradata() {
      this.result();
    },
    //计算公式
    result() {
      let newtotal = 0;
      this.iousGoodsForm.storage_list.map((e) => {
        if (e.storage_num != "") {
          newtotal += Number(e.storage_num);
        }
      });
      if (newtotal > 0) {
        console.log(this.$toFixed(newtotal), "222");
        this.iousGoodsForm.child_Allnum = this.$toFixed(newtotal);
        this.iousGoodsForm.storage_price = this.$toFixed(
          parseFloat(this.iousGoodsForm.ious_Allprice) /
            parseFloat(this.iousGoodsForm.child_Allnum)
        );
        this.iousGoodsForm.loss_num = this.$toFixed(
          this.iousGoodsForm.ious_initnum - this.iousGoodsForm.child_Allnum
        );
        console.log(this.iousGoodsForm.loss_num, "损耗");
        console.log(this.iousGoodsForm.storage_price, "单价");
        console.log("333");
      }
    },
    numberClear() {
      this.info.stock_out_num = 0;
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.allocation_index();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.allocation_index();
    },
    //改变页数
    changePage(page) {
      this.current.page = page;
      this.allocation_index();
    },
    // 列表
    allocation_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      allocation_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          res.data.list.list.map((e) => {
            e.goods_content = "";
            let str = "";
            if (e.type == 1) {
              if (e.goods.transfer == 1) {
                str = `${e.goods.name} ${e.stock_out_num}${e.stock_out_goods_spu.spu_unit.title}  --->
                ${e.goods.name} ${e.storage_num}${e.storage_goods_spu.spu_unit.title}`;
              } else if (e.goods.transfer == 0) {
                str = `${e.goods.name} 【${e.stock_out_goods_spu.spu_name.title}】  ${e.stock_out_num}${e.stock_out_goods_spu.spu_unit.title}  --->
                ${e.goods.name}【${e.storage_goods_spu.spu_name.title}】 ${e.storage_num}${e.storage_goods_spu.spu_unit.title}`;
              }
            } else if (e.type == 2) {
              str = `${e.goods.name}【${e.stock_out_goods_spu.spu_name.title}】 ${e.stock_out_num}${e.stock_out_goods_spu.spu_unit.title}  --->
                ${e.storage_goods.name}【${e.storage_goods_spu.spu_name.title}】 ${e.storage_num}${e.storage_goods_spu.spu_unit.title}`;
            }
            if (e.type == 3) {
              e.allocationList.map((c) => {
                c.newstr = `${c.goods.name}【${c.goods_spu.spu_name.title}】${c.storage_num} 【${c.goods_spu.spu_unit.title}】库存价：${c.storage_price}`;
                str = `${e.goods.name}【${e.stock_out_goods_spu.spu_name.title}】${e.storage_num} ${e.stock_out_goods_spu.spu_unit.title} `;
              });
            }
            e.goods_content = str;
          });
          this.totalCount = res.data.list.total;
          this.typeList = res.data.type_list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //处理时间格式
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";

      return form;
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
    },
    // 导出SKU调拨
    exportAllocation() {
      this.exportVisible = true;
    },
    // 选择调拨类型
    allotTypeDia() {
      this.allot_type_show = true;
    },
    //根据类型显示
    changeAllotType(type) {
      switch (type) {
        case 1:
          this.$nextTick(() => {
            this.addedFormVisible = true;
          });
          break;
        case 2:
          this.$nextTick(() => {
            this.asyncGoodsVisible = true;
          });
          break;
        case 3:
          this.$nextTick(() => {
            this.iousVisible = true;
          });
          break;
      }
    },
    //白条分割删除事件
    delchild(index) {
      this.iousGoodsForm.storage_list.splice(index, 1);
      if (this.iousGoodsForm.storage_list.length > 0) {
        this.result();
      } else {
        this.iousGoodsForm.child_Allnum = 0;
        this.iousGoodsForm.loss_num = 0;
        this.iousGoodsForm.storage_price = 0;
      }
    },
    //清除事件
    clearData() {
      this.iousGoodsForm.value = "";
      this.$refs.iousSelect.activated = false;
      this.iousGoodsForm.storage_list = [];
      this.iousGoodsForm.price = 0;
      this.iousGoodsForm.money = 0;
      this.iousGoodsForm.ious_initnum = "";
      this.iousGoodsForm.ious_Allprice = 0;
      this.iousGoodsForm.child_Allnum = 0;
      this.iousGoodsForm.loss_num = 0;
      this.iousGoodsForm.storage_price = 0;
      this.iousGoodsForm.ious_inventory = 0;
      this.iousGoodsForm.ious_unit = "";
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 100px);
    .el-form-item {
      margin-bottom: 10px;
      &:last-child {
        margin-bottom: 4px;
      }
    }
  }
}

// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
}
.maintip {
  text-align: center;
  padding-top: 15px;
  font-size: 18px;
  span {
    display: inline;
    padding: 18px 0;
    color: red;
  }
}
.type1 {
  color: #03a98e;
}
.type2 {
  color: red;
}
.type3 {
  color: #e47c02;
}
// 导入
.importForm {
  display: flex;
  align-items: center;
  justify-content: center;
}
.allot_type_container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  & > div {
    width: 90px;
    height: 90px;
    margin: 10px 0;
    text-align: center;
    line-height: 90px;
    font-size: 14px;
    color: #585858;
    border: 1px solid #DCDFE6;
    cursor: pointer;
    border-radius: 8px;
    &:hover {
      color: #03a98e;
      border-color: #03a98e;
    }
  }
}
.main_dialog_copy {
  /deep/ .el-dialog {
    margin-top: 30vh !important;
  }
}
/deep/.main_table .el-table--small td .cell {
  height: auto;
}
/deep/.el-input--suffix .el-input__inner {
  padding-right: 0px;
}
/deep/.el-message-box__wrapper .el-button:focus,
.el-message-box__wrapper .el-button:hover,
.el-dialog__wrapper .el-button:focus,
.el-dialog__wrapper .el-button:hover {
  background: #03a98e;
  border-color: #03a98e;
  color: white;
}
.flexs {
  display: flex;
  flex-direction: column;
  text-align: left;
  margin-left: 10px;
}
.dialog_footer {
  justify-content: flex-end;
  display: flex;
  margin-top: 20px;
}
/deep/.el-input-number.is-without-controls .el-input__inner {
  text-align: left;
}

.goods-content-green {
  color: #67c23a;
}
.goods-content-flex {
  display: flex;
  justify-content: center;
}
</style>